﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace ZhCun.Framework.Common.Helpers
{
    /// <summary>
    /// 文件操作类
    /// </summary>
    public class FileHelper
    {
        /// <summary>
        /// 指定内容写如文本文件,如果文件存在则打开不存在则创建
        /// </summary>
        /// <param name="fullPath">包含文件名的文件名</param>
        /// <param name="content">内容</param>
        public static void TextFileWrite(string fullPath, string content)
        {
            using (FileStream aFile = new FileStream(fullPath, FileMode.OpenOrCreate))
            {
                using (StreamWriter sw = new StreamWriter(aFile))
                {
                    sw.Write(content);
                    sw.Close();
                }
            }
        }
        /// <summary>
        /// 根据文件名读取文本文件内容
        /// </summary>
        /// <param name="fullPath">包含路径的完成文件名</param>
        /// <returns>返回文本 内容</returns>
        public static string TextFileRead(string fullPath)
        {
            using (FileStream aFile = new FileStream(fullPath, FileMode.Open))
            {
                using (StreamReader sr = new StreamReader(aFile))
                {
                    string r = null;
                    r = sr.ReadToEnd();
                    return r;
                }
            }
        }
        /// <summary>
        /// 获得文件的MD5十六进制字符串
        /// </summary>
        public static string GetFileMD5Hex(string fileName)
        {
            byte[] md5Val = GetFileMD5Byte(fileName);
            string md5HexVal =  NumberHelper.ByteArrToHex(md5Val);
            return md5HexVal;
        }
        /// <summary>
        /// 获得文件的MD5十六进制字符串
        /// </summary>
        public static byte[] GetFileMD5Byte(string fileName)
        {
            using (FileStream file = new FileStream(fileName, FileMode.Open))
            {
                System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] md5Val = md5.ComputeHash(file);
                return md5Val;
            }
        }
    }
}
